package com.yzt.zhuju.utils

import android.content.Context
import android.net.Uri
import android.text.TextUtils
import com.luck.picture.lib.engine.CompressFileEngine
import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener
import top.zibin.luban.Luban
import top.zibin.luban.OnNewCompressListener
import java.io.File
import java.util.*

/**
 * 图片压缩
 */
class McImageCompressEngine private constructor() : CompressFileEngine {
    companion object {
        val instance: McImageCompressEngine by lazy { McImageCompressEngine() }
    }

    override fun onStartCompress(
        context: Context?,
        source: ArrayList<Uri>?,
        call: OnKeyValueResultCallbackListener?
    ) {
        Luban.with(context)
            .ignoreBy(1)
            .load(source)
            .filter { path ->
                !(TextUtils.isEmpty(path) || path!!.lowercase(Locale.getDefault())
                    .endsWith(".gif"))
            }
            .setRenameListener {
                val lastIndex: Int = it.lastIndexOf(".")
                val postfix = if (lastIndex != -1) it.substring(lastIndex) else ".jpg"
                return@setRenameListener "CMP_" + System.currentTimeMillis() + postfix
            }
            .setCompressListener(object : OnNewCompressListener {
                override fun onStart() {
                }

                override fun onSuccess(source: String?, compressFile: File?) {
                    if (call != null) {
                        var absolutePath: String? = null
                        if (compressFile?.isFile == true) {
                            absolutePath = compressFile.absolutePath
                        }
                        call.onCallback(source, absolutePath)
                    }
                }

                override fun onError(source: String?, e: Throwable?) {
                    call?.onCallback(source, null)
                }
            })
            .launch()
    }
}